<?php

namespace app\beautiful\model\mall;

use app\beautiful\model\goods\GoodsGroupModel;
use app\beautiful\model\goods\GoodsOtherSkuDetailModel;
use app\beautiful\model\LevelModel;
use app\beautiful\model\order\GoodsOrderItemModel;
use app\beautiful\model\order\OrderGoodsModel;
use app\common\model\CommonModel;
use app\common\model\ProduceDepartModel;
use app\stores\model\cash\CashCategoryModel;
use app\stores\model\order\GoodsOrderModel;
use think\facade\Db;


class GoodsModel extends CommonModel{

    protected  $name = 'beautiful_goods';

    protected  $pk   = 'goods_id';

    protected $type=[

        'rotation'=>'array',

        //'goods_details'=>'array'

    ];

    public function getById($where,$field='*')
    {
        $json = [];
        if($field=='*'){
            $json[] = 'discount_detail';
        }else{
            $arr = explode(',',$field);
            if(in_array('discount_detail',$arr)){
                $json[] = 'discount_detail';
            }
        }
        $list = $this->where($where)->json($json,true)->field($field)->find();

        if($list && $list['origin_type']==2){
            $cash_category = CashCategoryModel::info(['category_id'=>$list['cash_category_id'],'is_delete'=>0]);
            $online_category = CashCategoryModel::info(['category_id'=>$list['online_category_id'],'is_delete'=>0]);

            $list['cash_category_name'] = $cash_category?$cash_category['name']:null;
            $list['online_category_name'] = $online_category?$online_category['name']:null;

            if($list['vip_discount_type']>0 && $list['discount_detail']){
                $l_model = new LevelModel();
                $discount_detail = $list['discount_detail'];
                foreach ($discount_detail as $k=>$v){
                    $level = $l_model->getById(['level_id'=>$v['level_id'],'shop_id'=>$list['shop_id'],'is_delete'=>0]);
                    $discount_detail[$k]['name']=$level?$level['name']:null;
                }
                $list['discount_detail'] = $discount_detail;

            }
        }




        return $list;
    }


    public function unit()

    {

        return $this->hasOne(GoodsOtherSkuDetailModel::class,'other_sku_detail_id','unit_id');

    }
    public function categoty()

    {

        return $this->hasMany(GoodsCategoryModel::class,'category_id','category_id');

    }
    public function goodsGroup()

    {

        return $this->hasMany(GoodsGroupModel::class,'goods_id','goods_id');

    }

    public function sku()

    {

        return $this->hasMany(GoodsSkuModel::class,'goods_id','goods_id');

    }

    public function findsku()

    {

        return $this->hasOne(GoodsSkuModel::class,'goods_id','goods_id');

    }



    public function getPreSaleTimeAttr($value,$data)

    {

        return $data['yu_days']>0 ? date("m月d日",strtotime("+".$data['yu_days']." day")) : '';

    }
    public static function list($where,$order,$page=1,$limit=10,$field='*'){
        $query = Db::name('beautiful_goods')->alias('g')
            ->leftJoin('beautiful_goods_other_sku_detail sd','sd.other_sku_detail_id=g.unit_id')
            ->where(['g.is_delete'=>0])
            ->when(isset($where['shop_id']),function ($query) use ($where){
                $query->where(['g.shop_id'=>$where['shop_id']]);
            })
            ->when(!empty($where['status']),function ($query) use ($where){
                $query->where(['g.status'=>$where['status']]);
            })
            ->when(!empty($where['type']),function ($query) use ($where){
                $query->where(['g.type'=>$where['type']]);
            })
            ->when(!empty($where['is_tui']),function ($query) use ($where){
                $query->where(['g.is_tui'=>$where['is_tui']]);
            })
            ->when(isset($where['online_sales']),function ($query) use ($where){
                $query->where(['g.online_sales'=>$where['online_sales']]);
            })
            ->when(isset($where['category_id']),function ($query) use ($where){
                $query->where(['g.category_id'=>$where['category_id']]);
            })
            ->when(isset($where['origin_type']),function ($query) use ($where){
                $query->where(['g.origin_type'=>$where['origin_type']]);
            })
            ->when(isset($where['cash_category_id']),function ($query) use ($where){
                $query->where(['g.cash_category_id'=>$where['cash_category_id']]);
            })
            ->when(isset($where['online_category_id']),function ($query) use ($where){
                $query->where(['g.online_category_id'=>$where['online_category_id']]);
            })
            ->when(isset($where['search']),function ($query) use ($where){
                $query->where('g.name', 'like', '%'.$where['search'].'%');
            })
            ->field($field);
        $count = $query->count();
        $list=$query->order($order)
            ->limit($limit)->page($page)
            ->select()
            ->toArray();
        if(!empty($list)){
            foreach ($list as &$v){
                $v['discount_detail'] = json_decode($v['discount_detail'],true);
                $v['sku'] = GoodsSkuModel::list(['shop_id'=>$v['shop_id'],'goods_id'=>$v['goods_id']],['gs.add_time'=>'asc'],1,999,'gs.*,sd.group_detail_name as unit');
                $order_ids = GoodsOrderModel::where(['shop_id'=>$v['shop_id'],'is_paid'=>1])->column('order_id');
                $v['order_count'] = GoodsOrderItemModel::whereIn('order_id',$order_ids)->where(['shop_id'=>$v['shop_id'],'goods_id'=>$v['goods_id'],'type'=>2])->group('order_id')->sum('goods_num');
                $v['order_count']+=$v['fictitious_take_count'];
                if(isset($v['origin_type']) && in_array($v['origin_type'],[2,3])){
                    $v = self::listInfo($v);
                }
            }
        }
        return compact('count','list');
    }

    static function listInfo($data){
        //最低折扣
        if($data['vip_discount_type']==1){

            $member_price = array_column($data['discount_detail'], 'member_price');

            $min_price = [
                'min_discount'=>min($member_price),

                'min_price'=>min($member_price) * $data['original_price']
            ];

        }else if($data['vip_discount_type']==2){

            $bid_price = array_column($data['discount_detail'], 'bid_price');

            $min_price = [
                'min_discount'=>min($bid_price),

                'min_price'=>min($bid_price)
            ];
        }else if($data['vip_discount_type']==3){
            $reduce_price = array_column($data['discount_detail'], 'reduce_price');

            $min_price = [
                'min_discount'=>max($reduce_price),

                'min_price'=>$data['original_price']-max($reduce_price)
            ];

        }else{
            $min_price = [];
        }
        if($data['origin_type']==3) $data['status'] = $data['online_status'];
        $cash_category = CashCategoryModel::info(['category_id'=>$data['cash_category_id'],'is_delete'=>0]);
        $online_category = CashCategoryModel::info(['category_id'=>$data['online_category_id'],'is_delete'=>0]);
        $depart = ProduceDepartModel::info(['id'=>$data['produce_depart_id'],'is_delete'=>0]);
        $support_service_type = $data['support_service_type']?explode(',',$data['support_service_type']):[];
        $data['min_discount'] = $min_price;
        $data['depart_name'] = $depart?$depart['name']:null;
        $data['cash_category_name'] = $cash_category?$cash_category['name']:null;
        $data['online_category_name'] = $online_category?$online_category['name']:null;
        $data['is_wm'] = ($support_service_type && in_array(3,$support_service_type))?1:0;
        if(!$data['sku']){
            $data['sku'][] = [
                'name'=>$data['name'],
                'crossed_price'=>$data['crossed_price'],
                'discount_detail'=>$data['discount_detail']
            ] ;
        }
        return $data;
    }

    public static function up($data,$where){
        $data['update_time'] = time();
        $res = self::update($data,$where);
        return $res;

    }


}

